<template>
  <main class="mt40">
    <n-form
        ref="formRef"
        :rules="rules"
        :model="model"
        label-placement="left"
        label-width="180"
        :style="{ maxWidth: '640px' }">
      <n-form-item label="注册账号（可用于登录）" path="account">
        <n-input v-model:value.trim="model.account" maxlength="60" placeholder="注册账号"/>
      </n-form-item>
      <n-form-item label=" " path="" class="mt10">
        <n-button round type="primary" @click="handleValidateButtonClick">
          保存账号
        </n-button>
      </n-form-item>
    </n-form>
  </main>
</template>
<script setup>
const formRef = ref({})
const userStore = useStore.userState()
const model = ref({
  id: '',
  account:'',
})

const rules = {
  account: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入用户名！'
  }
}

// 加载用户信息
const handleLoadUserInfo = async () => {
  const resp = await useLoadUserGetApi()
  if(resp && resp.data) {
    model.value = resp.data
    userStore.uuid = resp.data.uuid
    userStore.account = resp.data.account
    userStore.username = resp.data.username
    userStore.nickname = resp.data.nickname
    userStore.avatar = resp.data.avatar
    userStore.role = resp.data.role
    userStore.authorFlag = resp.data.authorFlag
    userStore.teacherFlag = resp.data.teacherFlag
  }
}


const handleValidateButtonClick = () => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        const resp = await useUpdateUserSettingsAccountApi(model.value)
        useMessage().success("修改账号成功!")
        userStore.account = model.value.account
      } catch (e) {
        useMessage().error(e.message)
        model.value.account = ""
      }
    }
  })
}

// 改变省份
const handleChangeProvince = (e) => {
  var cindex = provinceAndCityData.findIndex(c => c.label == e)
  if (pindex.value == cindex) return
  pindex.value = cindex
  model.value.province = e
  model.value.city = ''
}

onMounted(() => {
  handleLoadUserInfo()
})
</script>